﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using FileSysExp.Core;
using FileSysExp.Models;

namespace FileSysExp
{
    public class FileSystemManager
    {
        private static readonly Lazy<FileSystemManager> _Instance =
        new Lazy<FileSystemManager>(() => new FileSystemManager());

        private FileSystemManager()
        { }

        public static FileSystemManager Instance()
        {
            return _Instance.Value;
        }

        public List<IFileSysItem> GetDirectories(IFileSysItem parent)
        {
            List<IFileSysItem> list = new List<IFileSysItem>();
            List<string> dirs = new List<string>();
            dirs = Directory.EnumerateDirectories(parent.Name).ToList();
            foreach (string s in dirs)
            {
                IFileSysItem dm = new DirItemViemModel();
                dm.Name = s;
                dm.ShortName = dm.ShortName = s.Split('\\').Last();
                dm.Icon = Win32ApiNativeMethods.GetIcon(s);
                list.Add(dm);
            }
            return list;
        }

        public List<IFileSysItem> GetFiles(IFileSysItem parent)
        {
            List<IFileSysItem> list = new List<IFileSysItem>();
            List<string> files = new List<string>();
            files = Directory.EnumerateFiles(parent.Name).ToList();
            string[] sizes = { "B", "KB", "MB", "GB" };
            foreach (string s in files)
            {
                FileItemViewModel fi = new FileItemViewModel();
                fi.Name = s;
                fi.ShortName = s.Split('\\').Last();
                fi.ModifiedDate = File.GetLastAccessTime(s).ToShortDateString();

                double len = new FileInfo(s).Length;
                int order = 0;
                while (len >= 1024 && order + 1 < sizes.Length)
                {
                    order++;
                    len = len / 1024;
                }

                fi.Size = String.Format("{0:0.##} {1}", len, sizes[order]);
                fi.Icon = Win32ApiNativeMethods.GetIcon(s);
                list.Add(fi);

            }

            return list;
        }
    }
}
